from django.conf import settings
from django.shortcuts import render_to_response
from django import forms
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect,HttpResponseNotFound
from django.template import RequestContext,loader
from django.contrib.auth.decorators import login_required,user_passes_test
from django.utils.translation import gettext_lazy as _

from pacs.models import Goal,Problem,Test,Task
from forms_admin import AddGoalManipulator

@user_passes_test(lambda u: u.has_perm("pacs.add_goal"))
def add_goal(request,task_slug):

	c = RequestContext(request)
	try:
		task = Task.objects.get(slug=task_slug)
	except Task.DoexNotExist:
		return None
	c['problem'] = task.problem
	manipulator = AddGoalManipulator()
	if request.POST:
		data = request.POST.copy()
		data.update(request.FILES)
		errors = manipulator.get_validation_errors(data)
		if not errors:
				manipulator.do_html2python(data)
				tests = [Test.objects.get(id=int(id)) for id in data['tests'].split(',')]
				goal = Goal(task=task,resultsTime=data['resultsTime'],maxPoints=int(data['maxPoints']),scoringWay=data['scoringWay'])
				goal.save() #instance needs to have a primary key value before a many-to-many relationship can be used
				goal.tests = tests
				goal.save()
				for test in tests:
					if data['resultsTime'] < test.checkTime:
						test.checkTime = data['resultsTime'] #we need test checked, to publish goal
				return HttpResponseRedirect(reverse("pacs.views.add_goal",None,(),{'task_slug':task_slug}))
	else:
		now = task.startTime
		def cut_milis(s):
			return s[:s.find('.')]
		data = {'resultsTime':cut_milis(now.isoformat(' '))}
		errors = {}
	c['form'] = forms.FormWrapper(manipulator,data,errors)
	return render_to_response('pacs/add_goal.xhtml', c)
